import { message } from 'antd';
import { statusCodeEnum } from 'src/interface';
import { HttpRequest } from 'src/utils/request';
import { getToken } from 'src/utils/storage';
import { t } from 'src/locales';

const http = new HttpRequest({
  baseURL: import.meta.env.VITE_BASE_URL_PREFIX,
});

http.setRequestInterceptors((config) => {
  // 提醒网络错误
  if (!navigator.onLine) {
    message.error(t('request.networkError'));
    return Promise.reject();
  }
  const token = getToken();
  config.headers.Authorization = `Bearer ${token}`;
  return config;
});

http.setResponseInterceptors(
  (config) => {
    const data = config.data ?? null;
    if (Number(data?.code) === statusCodeEnum.ERROR) {
      message.error(data?.msg ?? '请求错误，请稍后重试');
      return Promise.reject();
    }
    return data;
  },
  (error) => {
    const status = error?.response?.status;
    if (status) {
      message.error(t(`request.exception.${status}`));
    }
  },
);

export default http;
